<template>
  <div class="table-page" ref="tableRef">
    <!-- 文章列表 -->
    <div class="title-box">查询表格</div>
    <a-form label-align="right" auto-label-width :model="form" class="form">
      <a-row :gutter="16" wrap>
        <a-col :xs="12" :md="12" :lg="8" :xl="6" :xxl="6">
          <a-form-item field="keyword" label="关键词">
            <a-input v-model="form.keyword" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :xs="12" :md="12" :lg="8" :xl="6" :xxl="6">
          <a-form-item field="title" label="文章标题">
            <a-input v-model="form.title" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :xs="12" :md="12" :lg="8" :xl="6" :xxl="6">
          <a-form-item field="push_system" label="推送平台">
            <a-cascader :options="pushSystemOptions" v-model="form.push_system" placeholder="请选择" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :xs="12" :md="12" :lg="8" :xl="6" :xxl="6">
          <a-form-item field="status" label="推送状态">
            <a-select v-model="form.status" placeholder="请选择" allow-clear>
              <a-option value="-1">{{ statusMap['-1'].name }}</a-option>
              <a-option value="0">{{ statusMap['0'].name }}</a-option>
              <a-option value="1">{{ statusMap['1'].name }}</a-option>
              <a-option value="2">{{ statusMap['2'].name }}</a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xs="12" :md="12" :lg="8" :xl="6" :xxl="6">
          <a-form-item field="create_time" :width="180" label="创建时间">
            <a-range-picker v-model="form.create_time" />
          </a-form-item>
        </a-col>
        <a-col :xs="12" :md="12" :lg="8" :xl="6" :xxl="6">
          <a-space>
            <a-button type="primary" @click="getTableData">
              <template #icon>
                <icon-search />
              </template>
              <template #default>查询</template>
            </a-button>
            <a-button @click="handleReset">
              <template #default>重置</template>
            </a-button>
          </a-space>
        </a-col>
        <a-col :xs="12" :md="12" :lg="8" :xl="12" :xxl="12">
          <a-space style="width: 100%; justify-content: flex-end">
            <a-button type="primary" shape="circle" @click="handleOpenStatusTable">
              <template #icon>
                <icon-upload />
              </template>
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-form>
    <section class="table-box">
      <a-table
        row-key="id"
        size="small"
        page-position="bl"
        :bordered="{ cell: true }"
        :loading="loading"
        :data="tableData"
        :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
        :pagination="{ showPageSize: true, showTotal: true, total: total, current: current, pageSize: pageSize }"
        @page-change="changeCurrent"
        @page-size-change="changePageSize"
      >
        <template #columns>
          <a-table-column title="ID" :width="68" data-index="id"> </a-table-column>
          <a-table-column title="关键词" :min-width="180" data-index="keywords"></a-table-column>
          <a-table-column title="推送平台">
            <template #cell="{ record }">
              {{ record.pushsys?.name || '' }}
              {{ record.pushchanl ? `/${record.pushchanl.name}` : '' }}
            </template>
          </a-table-column>
          <a-table-column title="文章标题" :min-width="180" data-index="title"></a-table-column>
          <a-table-column title="创建时间" data-index="createtime" :width="180"></a-table-column>
          <a-table-column title="推送状态" :width="120" data-index="status">
            <template #cell="{ record }">
              <a-tag :color="statusMap[record.status]?.color">{{ statusMap[record.status]?.name }}</a-tag>
            </template>
          </a-table-column>
          <a-table-column title="审核人" :width="120" data-index="title">
            <template #cell="{ record }"> {{ record.admin?.username || '' }}</template>
          </a-table-column>
          <a-table-column title="操作" :width="200" align="center" fixed="right">
            <template #cell="{ record }">
              <a-space>
                <a-link v-if="record.status == 0" @click="handleOpenApproval(record.id, 'audit')">
                  <template #default>审核</template>
                </a-link>
                <a-link v-if="record.status == 1" @click="handleOpenApproval(record.id, 'view')">
                  <template #default>查看</template>
                </a-link>
                <a-popconfirm v-if="record.status != 1" content="确认推送?" @ok="handlePush(record)">
                  <a-link v-if="record.status == 2">
                    <template #default>推送</template>
                  </a-link>
                </a-popconfirm>
                <a-popconfirm v-if="record.status != 1" content="确认删除?" @ok="handleDelete(record)">
                  <a-link status="danger">
                    <template #default>删除</template>
                  </a-link>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </section>
    <Draggable
      @handleChooseKeyword="handleChooseKeyword"
      @handleInputKeyword="handleInputKeyword"
      :showOperation="showOperation"
      v-if="show"
      :parentRef="tableRef"
      :width="40"
      :height="40"
    >
      <img
        @click="showOperation = !showOperation"
        width="40px"
        class="dowload-button-img"
        src="@/icons/menu-form.svg"
        alt=""
      />
    </Draggable>
    <statusTable ref="statusTableRef"></statusTable>
    <addKeyWordRelationModal ref="addKeyWordRelationModalRef"></addKeyWordRelationModal>
  </div>
</template>

<script setup lang="ts" name="MainTable">
import { reactive, ref, onMounted, onBeforeUnmount } from 'vue'
import { usePagination } from '@/hooks'
import { getAuditList, deleteAudit, getKeyWordTypeList, getPushSystem, pushStatus } from '@/apis'
import { useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import { format } from 'date-fns'
import Draggable from './components/Draggable.vue'
import addKeyWordRelationModal from './components/addKeyWordRelationModal.vue'
import statusTable from './components/statusTable.vue'
import eventBus from '@/utils/eventBus'

const statusTableRef = ref(null)
const addKeyWordRelationModalRef = ref(null)
const showOperation = ref(true)
const show = ref(false)
const tableRef = ref(null)
const router = useRouter()
const form = reactive({
  keyword: '',
  title: '',
  push_system: '',
  create_time: [],
  status: ''
})
const statusMap = {
  '-1': {
    name: '存入废稿',
    color: 'gray'
  },
  '0': {
    name: '未审核',
    color: 'orange'
  },
  '1': {
    name: '已推送',
    color: 'green'
  },
  '2': {
    name: '推送失败',
    color: 'red'
  }
}
const loading = ref(false)
const tableData = ref([])

const { current, pageSize, total, changeCurrent, changePageSize, setTotal } = usePagination(() => getTableData())

const getTableData = async () => {
  loading.value = true
  let start_time = ''
  let end_time = ''
  if (form.create_time && form.create_time.length > 0) {
    start_time = format(form.create_time[0], 'yyyy-MM-dd 00:00:00')
    end_time = format(form.create_time[1], 'yyyy-MM-dd 23:59:59')
  }
  const resData = await getAuditList({
    page: current.value,
    pagesize: pageSize.value,
    keyword: form.keyword,
    title: form.title,
    push_system: form.push_system,
    status: form.status || null,
    end_time,
    start_time,
    type: 1
  })

  if (resData.code == 1) {
    tableData.value = resData.data.data.data
    setTotal(resData.data.data.total)
    loading.value = false
  } else {
    loading.value = false
    Message.error(resData.msg)
  }
}
const handleReset = () => {
  form.keyword = ''
  form.title = ''
  form.push_system = ''
  form.status = ''
  form.create_time = []
  getTableData()
}
getTableData()

// 获取联级菜单选项
// 树形遍历
function transformTree(data) {
  return data.map((node) => ({
    value: node.id,
    label: node.name,
    children: node?.child?.length > 0 ? transformTree(node.child) : null
  }))
}
const pushSystemOptions = ref([])
const getPushSystemOptions = async () => {
  const resData = await getPushSystem()

  if (resData.code == 1) {
    let system_channel = resData.data.system_channel || []
    pushSystemOptions.value = resData.data.push_system.map((dd) => {
      let isHave = system_channel.findIndex((cc) => cc.push_system_id === dd.id)
      let children = null
      if (isHave !== -1) {
        let temp = system_channel.filter((cc) => cc.push_system_id === dd.id)
        children = transformTree(temp)
      }
      return {
        value: dd.id,
        label: dd.name,
        children
      }
    })
  }
}
getPushSystemOptions()
onBeforeUnmount(() => {
  eventBus.$off('handleChangeAudit', getTableData)
})
onMounted(() => {
  eventBus.$on('handleChangeAudit', getTableData)
  show.value = true
})
// 输入关键词
const handleInputKeyword = () => {
  addKeyWordRelationModalRef.value.show()
}
// 关联关键词
const handleChooseKeyword = () => {
  console.log(234)

  router.push({ path: '/audit-management/relationKeyWords' })
}
const handleDelete = async (record) => {
  const resData = await deleteAudit({ post_id: record.id })
  if (resData.code == 1) {
    Message.success('删除成功')
    getTableData()
  } else {
    Message.error(resData.msg)
  }
}
const handlePush = async (record) => {
  const resData = await pushStatus({ post_id: record.id })
  if (resData.code == 1) {
    Message.success('推送成功')
    getTableData()
  } else {
    Message.error(resData.msg || '推送失败')
  }
}

const handleOpenApproval = (id, type) => {
  router.push({ path: '/audit-management/approve-page', query: { id, type, articleType: 1 } })
}
// 查看任务中表格
const handleOpenStatusTable = () => {
  statusTableRef.value.show()
}
</script>

<style lang="scss" scoped>
:deep(.arco-grid) {
  flex-wrap: wrap;
}
:deep(.arco-grid-item) {
  min-width: 250px;
}
:deep(.arco-alert-success) {
  padding: 14px 16px;
  border-color: rgb(var(--success-6));
  background-color: rgba(var(--success-6), 0.08);
  .arco-alert-content {
    color: rgb(var(--success-6));
    font-size: 12px;
  }
}
.table-page {
  position: relative;
  height: 100%;
  overflow: hidden;
  margin: $margin;
  background: var(--color-bg-1);
  padding: $padding;
  padding-bottom: 0;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  .title-box {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 8px;
  }
  .form {
    margin-top: 12px;
    :deep(.arco-form-item) {
      margin-bottom: 10px;
    }
  }
  .operation-line {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 8px 0;
  }
  .table-box {
    flex: 1;
    overflow: hidden;
    margin-top: 12px;
  }
}
</style>
